package org.example.domain.strategy.service.armory;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.activity.repository.IActivityRepository;
import org.example.domain.strategy.model.entity.StrategyAwardEntity;
import org.example.domain.strategy.model.entity.StrategyEntity;
import org.example.domain.strategy.model.entity.StrategyRuleEntity;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.types.common.Constants;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * @Author: PengHao
 * @CreateTime: 2025-07-11  11:08
 * @Description: 策略（装配库）兵工厂实现类，负责初始化策略计算
 */
@Service
@Slf4j
public class StrategyArmoryDispatch implements IStrategyArmory ,IStrategyDispatch{

    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = strategyRepository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    //装配奖池
    //把该奖池下的奖品存储到Redis中，生成乱序的奖品Map<序号，奖品ID>
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        //查询策略(奖品)配置
        List<StrategyAwardEntity>strategyAwardEntities = strategyRepository.queryStrategyAwardList(strategyId);
        if(strategyAwardEntities.isEmpty()||strategyAwardEntities == null){
            return false;
        }

        //将奖品库存缓存到redis
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCount = strategyAwardEntity.getAwardCount();
            cacheStrategyAwardCount(strategyId,awardId,awardCount);
        }


        //初始化全部奖池
        assembleLotteryStrategy(strategyId.toString(),strategyAwardEntities);

        StrategyEntity strategyEntity = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        if(strategyEntity == null) return true;

        String ruleWeight = strategyEntity.getRuleWeight();
        if(ruleWeight == null){
            return true;
        }

        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(strategyId, ruleWeight);
        if (strategyRuleEntity == null){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode());
        }

        //初始化不同权重的不同奖池
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        ruleWeightValueMap.forEach((key,value)->{
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entry->!value.contains(entry.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key),strategyAwardEntitiesClone);
        });

        return true;
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        strategyRepository.cacheStrategyAwardCount(cacheKey,awardCount);
    }

    //strategyId为redis的key
    public void assembleLotteryStrategy(String strategyId,List<StrategyAwardEntity>strategyAwardEntities){
        //查询最小概率
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //查询概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        //查询概率范围（总概率/最小概率，查出一共分多少组数据）
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        //设置奖品权重，不同概率占用table的数量不同
        List<Integer>strategyAwardSearchRateTable = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            BigDecimal awardRate = strategyAwardEntity.getAwardRate();
            for (int i = 0; i <rateRange.multiply(awardRate).setScale(0,RoundingMode.CEILING).intValue() ; i++) {
                strategyAwardSearchRateTable.add(strategyAwardEntity.getAwardId());
            }
        }
        //打乱顺序
        Collections.shuffle(strategyAwardSearchRateTable);

        //将List的数据转到hashMap中，方便我们有序的存入redis
        HashMap<Integer,Integer>shuffleAwardStrategySearchRateTable = new HashMap<>();
        for (int i = 0;i<strategyAwardSearchRateTable.size();i++) {
            shuffleAwardStrategySearchRateTable.put(i,strategyAwardSearchRateTable.get(i));
        }

        //存储到redis
        strategyRepository.storeStrateAwardSearchRateTable(strategyId,shuffleAwardStrategySearchRateTable.size(), shuffleAwardStrategySearchRateTable);

    }

    //根据策略ID获取随机该奖池下的一个奖品ID
    @Override
    public Integer getRandomAwardId(Long strategyId) {
        Integer rateRange = strategyRepository.getRateRange(strategyId.toString());
        return strategyRepository.getStrategyRandomAward(strategyId.toString(),new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightvalue) {
        String rangeKey = strategyId.toString().concat("_").concat(ruleWeightvalue);
        Integer rateRange = strategyRepository.getRateRange(rangeKey);
        return strategyRepository.getStrategyRandomAward(rangeKey,new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return strategyRepository.subtractionAwardStock(cacheKey, endDateTime);
    }
}
